package com.yuzhitong.shapi.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.bean.InfoBean;
import com.brsya.aliplayview.PlayLayout;
import com.brsya.videoprogressbar.VideoProgressBar;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.hpplay.sdk.source.easycast.IEasyCastListener;
import com.hpplay.sdk.source.easycast.bean.EasyCastBean;
import com.yuzhitong.shapi.R;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BaseMvpActivity;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.recycler.BaseAdapter;
import com.yuzhitong.shapi.base.recycler.BaseViewHolder;
import com.yuzhitong.shapi.bean.MovieBean;
import com.yuzhitong.shapi.bean.PlayHistoryBean;
import com.yuzhitong.shapi.bean.PlayListBean;
import com.yuzhitong.shapi.contract.PlayContract;
import com.yuzhitong.shapi.fragment.PlayInfoFragment;
import com.yuzhitong.shapi.fragment.PlayPartFragment;
import com.yuzhitong.shapi.fragment.PlayTypeFragment;
import com.yuzhitong.shapi.presenter.PlayPresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.AppUtil;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.util.UiUtil;
import com.yuzhitong.shapi.widget.ItemPartView;
import com.yuzhitong.shapi.widget.LoadingHintDialog;
import com.yuzhitong.shapi.widget.PlayLoadView;
import com.yuzhitong.shapi.widget.PlaySpeedPopupWindow;
import com.yuzhitong.shapi.widget.PlayTypeDialog;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.AutoSizeConfig;

/**
 * Created by Brsya
 * CreateDate: 2022/5/24  8:54
 * Description:
 * 播放页面
 */
public class PlayActivity extends BaseMvpActivity<PlayPresenter> implements PlayContract.View, View.OnClickListener {

    private LinearLayout llPlayTitleBox;
    private PlayLayout svPlayBox;
    private RelativeLayout rlPlayAdBox;
    private RelativeLayout rlTitleBack;
    private TextView tvPlayTitle;
    private RelativeLayout rlTitlePull;
    private RelativeLayout rlTitleBarrage;
    private LinearLayout llControlBox;
    private RelativeLayout rlControlPlay;
    private View vPlayPause;
    private TextView tvPlayTime;
    private VideoProgressBar pbPlay;
    private TextView tvPlayBigPart;
    private RecyclerView rlBigPartBox;
    private TextView tvPlayAllTime;
    private RelativeLayout rlControlFull;
    private TextView tvMovieName;
    private TextView tvBtnMovieInfo;
    private TextView tvMovieFraction;
    private TextView tvMovieLabel;
    private TextView tvMoviePartBtn;
    private TextView tvMovieTypeBtn;
    private RecyclerView rvPartList;
    private RelativeLayout rlAdBox;
    private TextView tvShowMoreDay;
    private LinearLayout llLikeBox;
    private RecyclerView rlRecommendList;
    private FrameLayout flFragmentBox;

    private boolean isPause = false;

    private AliPlayer aliPlayer;
    private Handler handler;
    private MovieBean movieBean;

    /**
     * 视频类型
     */
    private String videoType;
    /**
     * 隐藏控制栏
     */
    private Runnable hideTitleRunnable;

    private long hideTitleTime = 5000;
    /**
     * 点击播放器时间
     */
    private long playClickTime = 0;
    /**
     * 播放状态
     */
    private int playStatus;

    /**
     * 是否正在操作进度条
     */
    private boolean isTouch;

    private LoadingHintDialog loadingHintDialog;

    /**
     * 是否初次播放
     * 用于控制播放错误自动下一集
     */
    private boolean isInitPlay;

    /**
     * 可播放列表
     */
    private List<PlayListBean.PlayerListDTO> playerListDTO;

    /**
     * 正在播放的渠道id
     */
    private int typeIndex;
    /**
     * 正在播放的集数id
     */
    private int partIndex;


    /**
     * 分集适配器
     */
    private BaseAdapter<PlayListBean.PlayerListDTO.InfoListDTO> partAdapter;
    /**
     * 横版分集适配器
     */
    private BaseAdapter<PlayListBean.PlayerListDTO.InfoListDTO> partBigAdapter;

    /**
     * 猜你喜欢适配器
     */
    private BaseAdapter<MovieBean> likeAdapter;

    /**
     * 是否锁屏
     */
    private boolean isLock = false;

    /**
     * 进入页面自动播放
     */
    private boolean isAutoPlay = true;


    private PlayInfoFragment playInfoFragment;
    private PlayPartFragment partFragment;
    private PlayTypeFragment playTypeFragment;

    private ValueAnimator showLayoutAnimator;
    private ValueAnimator hideLayoutAnimator;
    private boolean fragmentShow;


    private List<PlayHistoryBean> playHistories;

    private long playTime = -1;


    private AdUtilManage adUtilManage;
    private AdUtilManage adUtilManagePage;
    private AdUtilManage adUtilManageBig;
    private RelativeLayout rlLbPull;
    private PlayLoadView lbvLoad;
    private LinearLayout llControlBoxBig;
    private RelativeLayout rlControlPlayBig;
    private View vPlayPauseBig;
    private RelativeLayout rlControlNextBig;
    private View vPlayNextBig;
    private TextView tvPlayTimeBig;
    private VideoProgressBar pbPlayBig;
    private TextView tvPlayAllTimeBig;
    private TextView tvPlayBigSpeedBig;
    private RelativeLayout rlControlFullBig;

    private PlaySpeedPopupWindow playSpeedPopupWindow;
    private LinearLayout llPlayLock;
    private View vLock;
    private LinearLayout llPlayTypeBox;
    private TextView tvVideoPlayError;
    private LinearLayout RlVideoPlayError;
    private TextView tvPlayType;
    private TextView tvPlayDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        UiUtil.setStatusDark(this, false);

        try {

            initData();

            initView();

            initViewData();

            loadViewData(null);

//            AutoSizeConfig.getInstance().setVertical(true)
//                    .setPrivateFontScale(0)
//                    .setExcludeFontScale(true);

            //        initPlay();

            // 加载列表广告
            if (adUtilManagePage == null) {
                adUtilManagePage = AdUtilManage.initShow(PlayActivity.this, rlAdBox, Contents.AD_TT_SDK_HOME_ID);
            }


        } catch (Exception ignored) {

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        loadViewData(intent);
    }

    private void loadViewData(Intent intent) {
        if (intent == null) {
            intent = getIntent();
        }
        if (intent != null) {
            if (intent.getSerializableExtra(Contents.INTENT_MOVIE_DETAIL) != null) {
                if (intent.getSerializableExtra(Contents.INTENT_MOVIE_DETAIL) instanceof MovieBean) {
                    movieBean = (MovieBean) intent.getSerializableExtra(Contents.INTENT_MOVIE_DETAIL);
                }
            }
        }
        partIndex = 0;
        playTime = 0;
        isInitPlay = true;
        tvVideoPlayError.setVisibility(View.VISIBLE);
        pbPlay.setProgressValue(0);
        pbPlayBig.setProgressValue(0);
        tvPlayTime.setText("00:00");
        tvPlayTimeBig.setText("00:00");

        if (movieBean == null) {
            Toast.makeText(this, "数据错误,请退出重试", Toast.LENGTH_SHORT).show();
            return;
        }
        for (PlayHistoryBean playHistory : playHistories) {
            if (playHistory.getMovieId() == movieBean.getId()) {
                partIndex = playHistory.getPartIndex();
                playTime = playHistory.getPlayTime();
            }
        }
        // 影视名称
        tvPlayTitle.setText(movieBean.getName());
        tvMovieName.setText(movieBean.getName());
        // 影视分数
        if (!StringUtil.isEmpty(movieBean.getDoubanScore())) {
            tvMovieFraction.setText(getResources().getString(R.string.play_movie_fraction, movieBean.getDoubanScore()));
        } else {
            tvMovieFraction.setText("");
        }
        // 影视标签
        tvMovieLabel.setText(AppUtil.getMovieTagListStr(movieBean));

        presenter.getHot(movieBean.getId());
        presenter.getLike(movieBean.getId(), movieBean.getVideoTag());
    }

    @Override
    protected void onDestroy() {
        AdUtilManage.destroy(adUtilManagePage);
        AdUtilManage.destroy(adUtilManage);
        if (aliPlayer != null) {
            aliPlayer.pause();
        }
        super.onDestroy();
    }

    @Override
    protected void initPresenter() {
        presenter = new PlayPresenter();
        presenter.attachView(this);
    }

    private void initData() {
        handler = new Handler(Looper.getMainLooper());
        String playHistoriesStr = MyApplication.aCache.getAsString(Contents.CACHE_KEY_HISTORY);
        if (StringUtil.isEmpty(playHistoriesStr)) {
            playHistories = new LinkedList<>();
        } else {
            playHistories = JSON.parseArray(playHistoriesStr, PlayHistoryBean.class);
        }
    }

    private void initView() {
        llPlayTitleBox = findViewById(R.id.ll_play_title_box);
        svPlayBox = findViewById(R.id.sv_play_box);
        rlTitleBack = findViewById(R.id.rl_title_back);
        tvPlayTitle = findViewById(R.id.tv_play_title);
        rlTitlePull = findViewById(R.id.rl_title_pull);
        rlTitleBarrage = findViewById(R.id.rl_title_barrage);
        llControlBox = findViewById(R.id.ll_control_box);
        rlControlPlay = findViewById(R.id.rl_control_play);
        vPlayPause = findViewById(R.id.v_play_pause);
        tvPlayTime = findViewById(R.id.tv_play_time);
        tvPlayAllTime = findViewById(R.id.tv_play_all_time);
        rlControlFull = findViewById(R.id.rl_control_full);
        pbPlay = findViewById(R.id.pb_play);
        tvMovieName = findViewById(R.id.tv_movie_name);
        tvBtnMovieInfo = findViewById(R.id.tv_btn_movie_info);
        tvMovieFraction = findViewById(R.id.tv_movie_fraction);
        tvMovieLabel = findViewById(R.id.tv_movie_label);
        tvMoviePartBtn = findViewById(R.id.tv_movie_part_btn);
        tvMovieTypeBtn = findViewById(R.id.tv_movie_type_btn);
        rvPartList = findViewById(R.id.rv_part_list);
        rlAdBox = findViewById(R.id.rl_ad_box);
        tvShowMoreDay = findViewById(R.id.tv_show_more_day);
        rlRecommendList = findViewById(R.id.rl_recommend_list);
        flFragmentBox = findViewById(R.id.fl_fragment_box);
        llLikeBox = findViewById(R.id.ll_like_box);
        tvPlayBigPart = findViewById(R.id.tv_play_big_part);
        rlBigPartBox = findViewById(R.id.rl_big_part_box);
        rlPlayAdBox = findViewById(R.id.rl_play_ad_box);
        rlLbPull = findViewById(R.id.rl_lb_pull);
        lbvLoad = findViewById(R.id.lbv_load);
        llControlBoxBig = findViewById(R.id.ll_control_box_big);
        rlControlPlayBig = findViewById(R.id.rl_control_play_big);
        vPlayPauseBig = findViewById(R.id.v_play_pause_big);
        rlControlNextBig = findViewById(R.id.rl_control_next_big);
        vPlayNextBig = findViewById(R.id.v_play_next_big);
        tvPlayTimeBig = findViewById(R.id.tv_play_time_big);
        pbPlayBig = findViewById(R.id.pb_play_big);
        tvPlayAllTimeBig = findViewById(R.id.tv_play_all_time_big);
        tvPlayBigSpeedBig = findViewById(R.id.tv_play_big_speed_big);
        rlControlFullBig = findViewById(R.id.rl_control_full_big);
        llPlayLock = findViewById(R.id.ll_play_lock);
        vLock = findViewById(R.id.v_lock);
        llPlayTypeBox = findViewById(R.id.ll_play_type_box);
        tvVideoPlayError = findViewById(R.id.tv_video_play_error);
        RlVideoPlayError = findViewById(R.id.rl_video_play_error);
        tvPlayType = findViewById(R.id.tv_play_type);
        tvPlayDetail = findViewById(R.id.tv_play_detail);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.rl_title_back) {
            // 返回
            onBackPressed();
        } else if (id == R.id.tv_play_detail) {
            // 进入详情页
            Intent intent = new Intent(this, MovieDetailActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, movieBean);
            startActivity(intent);
        } else if (id == R.id.ll_play_lock) {
            // 锁屏
            changeLock(!isLock);
        } else if (id == R.id.rl_control_next_big) {
            // 下一集
            playVideo(false, true);
        } else if (id == R.id.tv_play_big_speed_big) {
            // 倍速
            //            // 这里的view代表popupMenu需要依附的view
            //            PopupMenu popupMenu = new PopupMenu(PlayActivity.this, tvPlayBigSpeedBig);
            //            // 获取布局文件
            //            popupMenu.getMenuInflater().inflate(R.menu.speed_menu, popupMenu.getMenu());
            //            popupMenu.show();
            //            // 通过上面这几行代码，就可以把控件显示出来了
            //            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            //                @Override
            //                public boolean onMenuItemClick(MenuItem item) {
            //                    // 控件每一个item的点击事件
            //
            //                    int itemId = item.getItemId();
            //                    if (itemId == R.id.speed_2) {
            //                        aliPlayer.setSpeed(2f);
            //                    } else if (itemId == R.id.speed_1_5) {
            //                        aliPlayer.setSpeed(1.5f);
            //                    } else if (itemId == R.id.speed_1) {
            //                        aliPlayer.setSpeed(1f);
            //                    } else if (itemId == R.id.speed_0_5) {
            //                        aliPlayer.setSpeed(.5f);
            //                    }
            //                    return true;
            //                }
            //            });

//            AutoSize.autoConvertDensity(this, 780, false);
            if (playSpeedPopupWindow == null) {
                playSpeedPopupWindow = new PlaySpeedPopupWindow(this);

                playSpeedPopupWindow.setOnSpeedChangeListener(new PlaySpeedPopupWindow.OnSpeedChangeListener() {
                    @Override
                    public void onSpeedChange(float speed) {
                        if (aliPlayer == null) {
                            return;
                        }
                        aliPlayer.setSpeed(speed);
                        playSpeedPopupWindow.dismiss();
                        // 定时隐藏
                        handler.postDelayed(hideTitleRunnable, hideTitleTime);
                    }
                });
            }
            // 设置弹出的位置(控件，上下移动,左右移动)
            playSpeedPopupWindow.showUp(tvPlayBigSpeedBig);
            handler.removeCallbacks(hideTitleRunnable);


        } else if (id == R.id.rl_title_pull) {
            // 投屏
            if (aliPlayer == null) {
                return;
            }
            handler.removeCallbacks(hideTitleRunnable);
            controlVisibility(true);
            aliPlayer.pause();
            pullScreen();
        } else if (id == R.id.rl_title_barrage) {
            // 弹幕
        } else if (id == R.id.rl_control_play || id == R.id.rl_control_play_big) {
            // 播放暂停
            playOrPause();
        } else if (id == R.id.tv_play_big_part) {
            // 全屏选集
//            AutoSize.autoConvertDensity(this, 780, false);
            showBigPart();
        } else if (id == R.id.tv_btn_movie_info) {
            // 简介
//            AutoSize.autoConvertDensity(this, 360, true);
            FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
            if (playInfoFragment == null) {
                playInfoFragment = PlayInfoFragment.newInstance(movieBean, new PlayInfoFragment.OnCloseListener() {
                    @Override
                    public void onClose() {
                        onBackPressed();
                    }
                });
                bt.add(R.id.fl_fragment_box, playInfoFragment);
            } else {
                bt.show(playInfoFragment);
            }

            if (partFragment != null) {
                bt.hide(partFragment);
            }
            if (playTypeFragment != null) {
                bt.hide(playTypeFragment);
            }
            bt.commit();
            // 显示
            showFragmentBox();
        } else if (id == R.id.tv_movie_part_btn) {
            // 选集
//            AutoSize.autoConvertDensity(this, 360, true);
            FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
            if (partFragment == null) {
                PlayListBean.PlayerListDTO playerListDTO = this.playerListDTO.get(typeIndex);
                List<PlayListBean.PlayerListDTO.InfoListDTO> infoList = playerListDTO.getInfoList();
                partFragment = PlayPartFragment.newInstance(infoList, videoType, new PlayPartFragment.OnSelectPartListener() {
                    @Override
                    public void onSelectPart(int index, PlayListBean.PlayerListDTO.InfoListDTO infoBean) {
                        partIndex = index;
                        isInitPlay = false;
                        playVideo();
                        presenter.getLike(movieBean.getId(), movieBean.getVideoTag());
                    }

                    @Override
                    public void onClose() {
                        onBackPressed();
                    }
                });
                bt.add(R.id.fl_fragment_box, partFragment);
            } else {
                bt.show(partFragment);
            }
            if (playInfoFragment != null) {
                bt.hide(playInfoFragment);
            }
            if (playTypeFragment != null) {
                bt.hide(playTypeFragment);
            }

            bt.commit();

            // 显示
            showFragmentBox();
        } else if (id == R.id.ll_play_type_box || id == R.id.tv_play_type) {
            // 换源
            //            FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
            //            PlayListBean.PlayerListDTO playerListDTO = this.playerListDTO.get(typeIndex);
            //            if (playTypeFragment == null) {
            //                playTypeFragment = PlayTypeFragment.newInstance(this.playerListDTO, new PlayTypeFragment.OnSelectTypeListener() {
            //
            //                    @Override
            //                    public void onSelectType(int index, PlayListBean.PlayerListDTO infoBean) {
            //                        typeIndex = index;
            //                        partIndex = 0;
            //                        playVideo();
            //                        hideFragmentBox();
            //                    }
            //
            //                    @Override
            //                    public void onClose() {
            //                        onBackPressed();
            //                    }
            //                });
            //                playTypeFragment.setSelectType(playerListDTO.getPlayerName());
            //                bt.add(R.id.fl_fragment_box, playTypeFragment);
            //            } else {
            //                playTypeFragment.setSelectType(playerListDTO.getPlayerName());
            //                bt.show(playTypeFragment);
            //            }
            //            if (playInfoFragment != null) {
            //                bt.hide(playInfoFragment);
            //            }
            //            if (partFragment != null) {
            //                bt.hide(partFragment);
            //            }
            //            bt.commit();
            //            // 显示
            //            showFragmentBox();
            if (playerListDTO == null) {
                return;
            }
//            AutoSize.autoConvertDensity(this, 360, true);
            new PlayTypeDialog(this)
                    .setInfoList(this.playerListDTO)
                    .setOnSelectItemListener(new PlayTypeDialog.OnSelectItemListener() {
                        @Override
                        public void onDismiss() {

                        }

                        @Override
                        public void onSelect(int index, PlayListBean.PlayerListDTO infoBea) {
                            typeIndex = index;
                            partIndex = 0;
                            isInitPlay = false;
                            playVideo();
                            hideFragmentBox();
                            presenter.getLike(movieBean.getId(), movieBean.getVideoTag());
//                            AutoSize.autoConvertDensity(PlayActivity.this, 360, true);
                        }
                    })
                    .show();

            //            if (playerListDTO != null) {
            //                PopupWindow popupWindow = new PopupWindow(this, null);
            //                LinearLayout ll = new LinearLayout(this);
            //                ll.setOrientation(LinearLayout.VERTICAL);
            //                popupWindow.setContentView(ll);
            //                ll.setBackgroundResource(R.drawable.bg_play_type_popup);
            //                for (int i = 0; i < playerListDTO.size(); i++) {
            //                    PlayListBean.PlayerListDTO listDTO = playerListDTO.get(i);
            //                    TextView tv = new TextView(this);
            //                    tv.setText(listDTO.getPlayerName());
            //                    tv.setTextSize(16);
            //                    tv.setTextColor(0xFF333333);
            //                    tv.setTag(i);
            //                    tv.setPadding(40, 20, 40, 20);
            //                    tv.setOnClickListener(new View.OnClickListener() {
            //                        @Override
            //                        public void onClick(View v) {
            //                            typeIndex = (int) v.getTag();
            //                            partIndex = 0;
            //                            isInitPlay = false;
            //                            playVideo();
            //                            hideFragmentBox();
            //                        }
            //                    });
            //                    ll.addView(tv);
            //                }
            //                popupWindow.setBackgroundDrawable(null);
            //                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            //                popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            //                // 设置外部点击取消
            //                popupWindow.setOutsideTouchable(true);
            //                // 设置弹出的位置(控件，上下移动,左右移动)
            //                popupWindow.showAsDropDown(tvMovieTypeBtn, 0, 0);
            //            }


        } else if (id == R.id.rl_control_full || id == R.id.rl_control_full_big) {
            // 全屏
            changeScreen();
        }

    }

    private void changeLock(boolean isLock) {
        this.isLock = isLock;
        svPlayBox.setLock(isLock);
        vLock.setBackgroundResource(isLock ? R.mipmap.icon_lock : R.mipmap.icon_un_lock);
        if (isLock) {
            controlVisibility(false);
            handler.removeCallbacks(hideTitleRunnable);
        } else {
            controlVisibility(true);
            handler.postDelayed(hideTitleRunnable, hideTitleTime);
        }
    }

    /**
     * 显示横屏选集
     */
    private void showBigPart() {
        rlBigPartBox.setVisibility(View.VISIBLE);
    }

    /**
     * 显示fragment 选集 简介等
     */
    private void showFragmentBox() {
        if (showLayoutAnimator == null) {
            WindowManager manager = this.getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            int heightPixels = outMetrics.heightPixels;

            showLayoutAnimator = new ValueAnimator();
            showLayoutAnimator.setIntValues(heightPixels - svPlayBox.getBottom(), 0);
            showLayoutAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int value = (int) animation.getAnimatedValue();
                    flFragmentBox.setTranslationY(value);
                }
            });
            showLayoutAnimator.setDuration(300);
        }
        fragmentShow = true;
        flFragmentBox.setVisibility(View.VISIBLE);
        showLayoutAnimator.start();
    }

    /**
     * 隐藏fragment 选集 简介等
     */
    private void hideFragmentBox() {
        if (hideLayoutAnimator == null) {
            WindowManager manager = this.getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            int heightPixels = outMetrics.heightPixels;


            hideLayoutAnimator = new ValueAnimator();
            hideLayoutAnimator.setIntValues(0, heightPixels - svPlayBox.getBottom());
            hideLayoutAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int value = (int) animation.getAnimatedValue();
                    flFragmentBox.setTranslationY(value);
                }
            });
            hideLayoutAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    flFragmentBox.setVisibility(View.GONE);
                    fragmentShow = false;

                    FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
                    if (playTypeFragment != null) {
                        bt.hide(playTypeFragment);
                    }
                    if (playInfoFragment != null) {
                        bt.hide(playInfoFragment);
                    }
                    if (partFragment != null) {
                        bt.hide(partFragment);
                    }
                    bt.commit();

                }
            });
            hideLayoutAnimator.setDuration(300);
        }

        hideLayoutAnimator.start();
    }


    private IEasyCastListener iEasyCastListener;
    private IBrowseListener iBrowseListener;
    private IConnectListener connectListener;

    private boolean isInitPullScreen = false;

    /**
     * 投屏
     */
    private void pullScreen() {
        LoggerUtil.e("点击投屏 ");
        if (!isInitPullScreen) {

            if (iEasyCastListener == null) {
                iEasyCastListener = new IEasyCastListener() {
                    /**
                     * 如果没有触发此回调，则表示此次未搜索到设备或用户未投屏
                     */
                    @Override
                    public EasyCastBean onCast(LelinkServiceInfo lelinkServiceInfo) {
                        EasyCastBean bean = new EasyCastBean();
                        //实际需要投屏的url
                        bean.url = svPlayBox.getVideoUrl();
                        LoggerUtil.e("如果没有触发此回调，则表示此次未搜索到设备或用户未投屏");
                        return bean;
                    }

                    @Override
                    public void onCastError(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean, int i, int i1) {
                        //  如果投屏失败，在搜索页面关闭的时候，会触发回调
                        LoggerUtil.e("如果投屏失败，在搜索页面关闭的时候，会触发回调");
                    }

                    @Override
                    public void onCastLoading(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
                        // 推送成功 播放器停止播放
                        if (aliPlayer != null) {
                            aliPlayer.pause();
                        }
                        LoggerUtil.e("推送成功 ");
                    }

                    @Override
                    public void onCastPause(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
                        // 暂停
                        LoggerUtil.e("暂停 ");
                    }

                    @Override
                    public void onCastStart(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
                        // 起播 或 收端暂停之后恢复播放
                        if (aliPlayer != null && !isPause) {
                            aliPlayer.start();
                        }
                        LoggerUtil.e("起播 ");
                    }

                    @Override
                    public void onCastCompletion(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
                        // 收端播放结束，如果需要实现下一集，可在之后的onCast回调中提供播放信息
                        LoggerUtil.e("收端播放结束 ");
                    }

                    @Override
                    public void onCastPositionUpdate(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean, long l, long l1) {

                        LoggerUtil.e("onCastPositionUpdate ");
                    }

                    @Override
                    public void onCastStop(LelinkServiceInfo lelinkServiceInfo, EasyCastBean easyCastBean) {
                        // 搜索退出播放，不同于 onCastCompletion，此时需要恢复APP视频播放
                        LoggerUtil.e("搜索退出播放 ");
                    }

                    @Override
                    public void onDismiss() {
                        LoggerUtil.e("onDismiss ");
                        rlLbPull.setVisibility(View.GONE);
                    }
                };
            }
            if (iBrowseListener == null) {
                iBrowseListener = new IBrowseListener() {
                    @Override
                    public void onBrowse(int resultCode, List<LelinkServiceInfo> list) {
                        switch (resultCode) {
                            case IBrowseListener.BROWSE_ERROR_AUTH:
                                Toast.makeText(PlayActivity.this, "搜索超时", Toast.LENGTH_SHORT).show();
                                LoggerUtil.e("搜索超时");
                                break;
                            case IBrowseListener.BROWSE_TIMEOUT:
                                Toast.makeText(PlayActivity.this, "停止搜索", Toast.LENGTH_SHORT).show();
                                LoggerUtil.e("停止搜索");
                                break;
                            case IBrowseListener.BROWSE_STOP:
                                Toast.makeText(PlayActivity.this, "认证失败", Toast.LENGTH_SHORT).show();
                                LoggerUtil.e("认证失败");
                                break;
                            case IBrowseListener.BROWSE_SUCCESS:
                                Toast.makeText(PlayActivity.this, "搜索成功", Toast.LENGTH_SHORT).show();
                                LoggerUtil.e("搜索成功: " + JSON.toJSONString(list));
                                break;
                        }
                    }
                };
            }
            LelinkSourceSDK.getInstance().setBrowseResultListener(iBrowseListener);

            // 二 建立连接
            //            if (connectListener == null) {
            //                connectListener = new IConnectListener() {
            //
            //                    @Override
            //                    public void onConnect(LelinkServiceInfo serviceInfo, int connectType) {
            //                        Toast.makeText(PlayActivity.this, "连接", Toast.LENGTH_SHORT).show();
            //                        LoggerUtil.e("连接");
            //                        LelinkSourceSDK.getInstance().startPlayMediaImmed(serviceInfo, svPlayBox.getVideoUrl(), LelinkSourceSDK.MEDIA_TYPE_VIDEO, false);
            //                    }
            //
            //                    @Override
            //                    public void onDisconnect(LelinkServiceInfo serviceInfo, int what, int extra) {
            //                        Toast.makeText(PlayActivity.this, "连接断开", Toast.LENGTH_SHORT).show();
            //                        LoggerUtil.e("连接断开");
            //                    }
            //                };
            //            }
            //            LelinkSourceSDK.getInstance().setConnectListener(connectListener);
        }


        int isSuccess = LelinkSourceSDK.getInstance().setEasyCastListener(iEasyCastListener);

        if (isSuccess != 0) {
            Toast.makeText(PlayActivity.this, "此sdk包不支持该接入模式", Toast.LENGTH_SHORT).show();
            LoggerUtil.e("此sdk包不支持该接入模式");
            return;
        }
        LelinkSourceSDK.getInstance()
                .setSdkInitInfo(this, "20904", "2e1c1c9da548df82cc3a518dd3688863")
                .easyPush(rlLbPull);
        rlLbPull.setVisibility(View.VISIBLE);
    }


    @SuppressLint("ClickableViewAccessibility")
    private void initViewData() {
        UiUtil.setStatusPadding(this, llPlayTitleBox);
        UiUtil.setStatusPadding(this, rlLbPull);
        llControlBoxBig.setPadding(
                llControlBoxBig.getPaddingLeft() + UiUtil.getStatusBarHeightPx(this),
                llControlBoxBig.getPaddingTop(),
                llControlBoxBig.getPaddingRight(),
                llControlBoxBig.getPaddingBottom()
        );


        rlTitleBack.setOnClickListener(this);
        rlTitlePull.setOnClickListener(this);
        rlTitleBarrage.setOnClickListener(this);
        rlControlPlay.setOnClickListener(this);
        rlControlFull.setOnClickListener(this);
        tvBtnMovieInfo.setOnClickListener(this);
        tvMoviePartBtn.setOnClickListener(this);
        llPlayTypeBox.setOnClickListener(this);
        tvPlayBigPart.setOnClickListener(this);
        rlControlPlayBig.setOnClickListener(this);
        rlControlNextBig.setOnClickListener(this);
        rlControlFullBig.setOnClickListener(this);
        tvPlayBigSpeedBig.setOnClickListener(this);
        llPlayLock.setOnClickListener(this);
        tvPlayType.setOnClickListener(this);
        tvPlayDetail.setOnClickListener(this);


        hideTitleRunnable = new Runnable() {
            @Override
            public void run() {
                controlVisibility(false);
            }
        };

        VideoProgressBar.OnProgressChangeListener onProgressChangeListener = new VideoProgressBar.OnProgressChangeListener() {
            @Override
            public void changeProgress(long progress) {
                aliPlayer.seekTo(progress);
                if (handler != null) {
                    handler.removeCallbacks(hideTitleRunnable);
                    // 定时隐藏
                    handler.postDelayed(hideTitleRunnable, hideTitleTime);
                }
            }

            @Override
            public void changeProgressHint(long progress) {
                tvPlayTime.setText(StringUtil.generateTime(progress));
                tvPlayTimeBig.setText(StringUtil.generateTime(progress));
                handler.removeCallbacks(hideTitleRunnable);
            }
        };
        pbPlay.setOnProgressChangeListener(onProgressChangeListener);
        pbPlayBig.setOnProgressChangeListener(onProgressChangeListener);

        View.OnTouchListener onTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isTouch = true;
                        break;
                    case MotionEvent.ACTION_UP:
                        isTouch = false;
                        break;
                    default:
                        break;
                }
                return false;
            }
        };
        pbPlay.setOnTouchListener(onTouchListener);
        pbPlayBig.setOnTouchListener(onTouchListener);


        svPlayBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isLock) {
                    llPlayLock.setVisibility(llPlayLock.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                    return;
                }
                if (rlBigPartBox.getVisibility() == View.VISIBLE) {
                    rlBigPartBox.setVisibility(View.GONE);
                    return;
                }
                // 处理双击逻辑  start-----
                long clickTime = System.currentTimeMillis();
                if (clickTime - playClickTime < 400) {
                    // 双击
                    playOrPause();

                    playClickTime = 0;
                    return;
                }
                playClickTime = clickTime;
                // 处理双击逻辑  end-----

                // 判断标题是否显示
                if (llPlayTitleBox != null) {
                    if (llPlayTitleBox.getVisibility() == View.VISIBLE) {
                        controlVisibility(false);
                    } else {
                        controlVisibility(true);
                        if (handler != null && playStatus == 3) {
                            handler.removeCallbacks(hideTitleRunnable);
                            // 定时隐藏
                            handler.postDelayed(hideTitleRunnable, hideTitleTime);
                        }
                    }
                }

            }
        });
        svPlayBox.setTraceId("TestId");
        svPlayBox.setPlayListener(new PlayLayout.PlayListener() {
            @Override
            public void onInfo(InfoBean infoBean) {
                switch (infoBean.getCode()) {
                    case CurrentPosition:
                        //extraValue为当前播放进度，单位为毫秒
                        playTime = infoBean.getExtraValue();
                        pbPlay.setProgressValue((int) playTime);
                        pbPlayBig.setProgressValue((int) playTime);
                        long duration = svPlayBox.getAliPlayer().getDuration();
                        pbPlay.setMaxProgressValue((int) duration);
                        pbPlayBig.setMaxProgressValue((int) duration);
                        if (!isTouch) {
                            tvPlayTime.setText(StringUtil.generateTime(playTime));
                            tvPlayTimeBig.setText(StringUtil.generateTime(playTime));
                        }
                        break;
                    case BufferedPosition:
                        ////extraValue为当前缓冲进度，单位为毫秒
                        long extraValue = infoBean.getExtraValue();
                        pbPlay.setProgressSecondaryValue((int) extraValue);
                        pbPlayBig.setProgressSecondaryValue((int) extraValue);
                        break;
                }
            }

            @Override
            public void onStateChanged(int status) {
                playStatus = status;
                if (status == 3) {
                    // 保持屏幕开启
                    UiUtil.openScreen(PlayActivity.this, true);
                    vPlayPause.setBackgroundResource(R.mipmap.icon_play_pause);
                    vPlayPauseBig.setBackgroundResource(R.mipmap.icon_play_pause);
                    handler.postDelayed(hideTitleRunnable, hideTitleTime);

                    // 隐藏竖屏播放广告
                    hidePlayHide();

                } else {
                    // 清除保持屏幕开启
                    UiUtil.openScreen(PlayActivity.this, false);
                    vPlayPause.setBackgroundResource(R.mipmap.icon_play_play);
                    vPlayPauseBig.setBackgroundResource(R.mipmap.icon_play_play);
                    handler.removeCallbacks(hideTitleRunnable);
                }
            }

            @Override
            public void onLoadingBegin() {
                LoggerUtil.e("开始缓存");
            }

            @Override
            public void onLoadingProgress(int progress, float netSpeed) {
                LoggerUtil.e("缓存进度: " + progress + " , 网速: " + progress);
                if (progress < 100) {
                    showCacheLoading();
                }else{
                    hideCacheLoading();
                }
            }

            @Override
            public void onLoadingEnd() {
                LoggerUtil.e("结束缓存");
                hideCacheLoading();
            }

            @Override
            public void onPrepared() {
                if (!isPause) {
                    svPlayBox.getAliPlayer().start();
                }
                aliPlayer = svPlayBox.getAliPlayer();
                LoggerUtil.e("开始播放");
                tvVideoPlayError.setVisibility(View.GONE);
                RlVideoPlayError.setVisibility(View.GONE);
                long duration = svPlayBox.getAliPlayer().getDuration();
                pbPlay.setMaxProgressValue((int) duration);
                pbPlayBig.setMaxProgressValue((int) duration);
                tvPlayAllTime.setText(StringUtil.generateTime(duration));
                tvPlayAllTimeBig.setText(StringUtil.generateTime(duration));
                hideLoading();
            }

            @Override
            public void onError(ErrorInfo errorInfo) {
                LoggerUtil.e("播放失败" + errorInfo.getMsg());
                tvVideoPlayError.setVisibility(View.GONE);
                RlVideoPlayError.setVisibility(View.VISIBLE);
                hideLoading();
            }

            @Override
            public void onCompletion() {
                LoggerUtil.e("播放完成");
                playVideo(false, true);
            }
        });

        partAdapter = new BaseAdapter<PlayListBean.PlayerListDTO.InfoListDTO>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {

                return new BaseViewHolder(new ItemPartView(PlayActivity.this));
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, PlayListBean.PlayerListDTO.InfoListDTO data) {
                ItemPartView itemPartView = (ItemPartView) viewHolder.getItemView();
                itemPartView.setText(data.getInfoName());
                itemPartView.setPlayStatus(data.isPlay());
                itemPartView.setIndex(RealPosition);
            }
        };

        partAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<PlayListBean.PlayerListDTO.InfoListDTO>() {
            @Override
            public void onItemClick(int position, PlayListBean.PlayerListDTO.InfoListDTO data) {
                partIndex = position;
                isInitPlay = false;
                playVideo();
//                AutoSize.autoConvertDensity(PlayActivity.this, 360, true);
            }
        });

        rvPartList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvPartList.setAdapter(partAdapter);
        rvPartList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int px = UiUtil.dpToPx(PlayActivity.this, 10);
                view.setPadding(
                        parent.getChildAdapterPosition(view) == 0 ? px : 0,
                        0,
                        px,
                        0);

            }
        });

        partBigAdapter = new BaseAdapter<PlayListBean.PlayerListDTO.InfoListDTO>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(PlayActivity.this).inflate(R.layout.item_part_big, parent, false);
                return new BaseViewHolder(view);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, PlayListBean.PlayerListDTO.InfoListDTO data) {
                ConstraintLayout clPartBox = viewHolder.findViewById(R.id.cl_part_box_big);
                TextView tvPartText = viewHolder.findViewById(R.id.tv_part_text_big);
                View vPlayIcon = viewHolder.findViewById(R.id.v_play_icon_big);
                tvPartText.setText(data.getInfoName());
                if (data.isPlay()) {
                    vPlayIcon.setVisibility(View.VISIBLE);
                    clPartBox.setBackgroundResource(R.drawable.bg_part_big_select);
                    tvPartText.setTextColor(0xFF2363CA);
                } else {
                    vPlayIcon.setVisibility(View.GONE);
                    clPartBox.setBackgroundResource(R.drawable.bg_part_big_default);
                    tvPartText.setTextColor(0xFF6A6B6C);
                }
            }
        };
        partBigAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<PlayListBean.PlayerListDTO.InfoListDTO>() {
            @Override
            public void onItemClick(int position, PlayListBean.PlayerListDTO.InfoListDTO data) {
                partIndex = position;
                isInitPlay = false;
                playVideo();
            }
        });
        rlBigPartBox.setLayoutManager(new GridLayoutManager(this, 4));
        rlBigPartBox.setAdapter(partBigAdapter);

        rlRecommendList.setLayoutManager(new GridLayoutManager(this, 3));
        likeAdapter = new BaseAdapter<MovieBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(PlayActivity.this).inflate(R.layout.item_movie, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                viewHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                tvMovieTitle.setText(data.getName());
                GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);
            }
        };
        likeAdapter.setOnItemClickListener((position, data) -> {
            isInitPlay = false;
            isAutoPlay = false;
            if (aliPlayer != null) {
                aliPlayer.pause();
            }
            addHistory(movieBean);
            Intent intent = new Intent(PlayActivity.this, PlayActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
            startActivity(intent);
        });
        View bottomView = LayoutInflater.from(this).inflate(R.layout.item_no_more_data, null, false);
        likeAdapter.setBottomView(bottomView);
        rlRecommendList.setAdapter(likeAdapter);
    }

    private void showPlayAd() {
        isAutoPlay = false;

//        AutoSize.autoConvertDensity(this, 360, true);
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            if (adUtilManageBig != null) {
                AdUtilManage.destroy(adUtilManageBig);
            }
            rlPlayAdBox.setVisibility(View.GONE);
            adUtilManageBig = AdUtilManage.initBigVideo(this, Contents.AD_TT_SDK_PLAY_BIG);
        } else {
            if (adUtilManage != null) {
                AdUtilManage.destroy(adUtilManage);
            }
            rlPlayAdBox.removeAllViews();
            adUtilManage = AdUtilManage.initShow(PlayActivity.this, rlPlayAdBox, Contents.AD_TT_SDK_PLAY,
                    0,
                    new TTNativeExpressAd.AdInteractionListener() {
                        @Override
                        public void onAdDismiss() {
                            rlPlayAdBox.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAdClicked(View view, int i) {
                            rlPlayAdBox.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAdShow(View view, int i) {

                        }

                        @Override
                        public void onRenderFail(View view, String s, int i) {
                            rlPlayAdBox.setVisibility(View.GONE);
                        }

                        @Override
                        public void onRenderSuccess(View view, float v, float v1) {

                        }
                    });

        }
    }


    private void hidePlayHide() {
        rlPlayAdBox.setVisibility(View.GONE);
    }


    @Override
    public void onBackPressed() {


        if (LelinkSourceSDK.getInstance().isBrowseShowing()) {
            LelinkSourceSDK.getInstance().dismissBrowserUI();
            rlLbPull.setVisibility(View.GONE);
            return;
        }

        if (rlBigPartBox.getVisibility() == View.VISIBLE) {
            rlBigPartBox.setVisibility(View.GONE);

            return;
        }

        if (fragmentShow) {
            hideFragmentBox();
            return;
        }

        backClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPause = false;
        if (aliPlayer != null && isAutoPlay) {
            aliPlayer.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;


        if (aliPlayer != null) {
            aliPlayer.pause();
        }
        addHistory(movieBean);
    }

    private void playVideo() {
        playVideo(false, false);
    }

    /**
     * 播放
     */
    private void playVideo(boolean typeNext, boolean partNext) {
        showLoading();
        RlVideoPlayError.setVisibility(View.GONE);
        if (typeNext) {
            typeIndex++;
        }
        if (typeIndex >= playerListDTO.size()) {
            return;
        }
        PlayListBean.PlayerListDTO playerListDTO = this.playerListDTO.get(typeIndex);
        List<PlayListBean.PlayerListDTO.InfoListDTO> infoList = playerListDTO.getInfoList();
        if (partNext) {
            partIndex++;
        }
        tvMovieTypeBtn.setText(playerListDTO.getPlayerName());
        if (partIndex > infoList.size()) {
            if (isInitPlay) {
                if (infoList.get(0) != null) {
                    Intent intent = new Intent(this, WebPageActivity.class);
                    intent.putExtra(Contents.INTENT_H5_URL, infoList.get(0).getInfoUrl());
                    startActivity(intent);
                }
            }
            return;
        }
        for (int i = 0; i < infoList.size(); i++) {
            PlayListBean.PlayerListDTO.InfoListDTO info = infoList.get(i);
            if (i == partIndex) {
                String infoUrl = info.getInfoUrl();
                if (playerListDTO.getPlayerType() == 20) {
                    if (playTime > 0) {
                        svPlayBox.setPlayTime(playTime);
                        playTime = 0;
                    }
                    svPlayBox.setVideoUrl(infoUrl);
                } else {
                    if (MyApplication.playAddressBean == null) {
                        return;
                    }
                    //                    presenter.getPlayAddress(infoUrl);
                    presenter.getPlayAddressNew(MyApplication.playAddressBean.getUrl(), MyApplication.playAddressBean.getMethod(), infoUrl);
                }
                info.setPlay(true);
            } else {
                info.setPlay(false);
            }
        }


        // 设置简介分集等数据
        initMovieViewData(infoList);

    }

    /**
     * 设置简介分集等数据
     */
    private void initMovieViewData(List<PlayListBean.PlayerListDTO.InfoListDTO> infoList) {
        partAdapter.setDataList(infoList);
        partAdapter.notifyDataSetChanged();
        rvPartList.scrollToPosition(partIndex);
        partBigAdapter.setDataList(infoList);
        partBigAdapter.notifyDataSetChanged();
        rlBigPartBox.scrollToPosition(partIndex);
        rlBigPartBox.setVisibility(View.GONE);
        if (partFragment != null) {
            partFragment.setInfoList(infoList);
        }
    }

    /**
     * 播放暂停控制
     * 根据状态判断
     */
    private void playOrPause() {
        switch (playStatus) {
            case 5:
                // 停止
                aliPlayer.prepare();
            case 6:
                // 播放完成
                aliPlayer.seekTo(0);
            case 2:
                // 准备好中
            case 4:
                // 暂停中
                // 开始播放
                aliPlayer.start();

                // 隐藏竖屏播放广告
                hidePlayHide();
                return;
            case 3:
                // 播放中
                // 暂停
                aliPlayer.pause();
                showPlayAd();
                isAutoPlay = true;
                return;
            default:
                break;
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        AutoSize.autoConvertDensity(this, 360, true);
        // 隐藏竖屏播放广告
        hidePlayHide();
    }

    /**
     * 切换横竖屏
     */
    private void changeScreen() {
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) svPlayBox.getLayoutParams();
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            // 切换为竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
            layoutParams.height = 0;
            layoutParams.dimensionRatio = "36:23";
            llControlBoxBig.setVisibility(View.GONE);
            llPlayLock.setVisibility(View.GONE);
            llControlBox.setVisibility(View.VISIBLE);
//            AutoSize.autoConvertDensity(this, 360, true);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
//                    AutoSize.autoConvertDensity(PlayActivity.this, 360, true);
                }
            }, 1000);
        } else {
            // 切换为横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            layoutParams.height = ConstraintLayout.LayoutParams.MATCH_PARENT;
            llControlBoxBig.setVisibility(View.VISIBLE);
            llPlayLock.setVisibility(View.VISIBLE);
            llControlBox.setVisibility(View.GONE);
//            AutoSize.autoConvertDensity(this, 780, false);
        }
        controlVisibility(true);
        svPlayBox.setLayoutParams(layoutParams);
        hideFragmentBox();
    }

    /**
     * 点击返回
     */
    private void backClick() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            changeScreen();
            changeLock(false);
            return;
        }
        // 关闭保持屏幕开启
        UiUtil.openScreen(PlayActivity.this, false);
        finish();
    }

    /**
     * 控制标题,状态栏,视频控制栏显示与隐藏
     *
     * @param isVisibility 是否显示
     */
    private void controlVisibility(boolean isVisibility) {
        llPlayTitleBox.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            if (!isVisibility) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            UiUtil.navigationOrStatusVisibility(this, isVisibility);
            llControlBoxBig.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
            llPlayLock.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
            llControlBox.setVisibility(View.GONE);
        } else {
            UiUtil.statusVisibility(this, isVisibility);
            llControlBoxBig.setVisibility(View.GONE);
            llPlayLock.setVisibility(View.GONE);
            llControlBox.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void showLoading() {
        //        if (loadingHintDialog == null) {
        //            loadingHintDialog = new LoadingHintDialog(this);
        //        }
        //        loadingHintDialog.show();
        if (lbvLoad.getVisibility() == View.VISIBLE) {
            return;
        }
        lbvLoad.setVisibility(View.VISIBLE);
        lbvLoad.startLoop();
    }

    @Override
    public void hideLoading() {
        //        if (loadingHintDialog != null) {
        //            loadingHintDialog.dismiss();
        //        }
        lbvLoad.setVisibility(View.GONE);
    }


    public void showCacheLoading() {
        showLoading();
    }


    public void hideCacheLoading() {
        hideLoading();
    }

    @Override
    public void goDetail() {
        Intent intent = new Intent(this, MovieDetailActivity.class);
        intent.putExtra(Contents.INTENT_MOVIE_DETAIL, movieBean);
        startActivity(intent);
        finish();
    }

    @Override
    public void playListSuccess(PlayListBean playListBean) {
        if (playerListDTO == null) {
            playerListDTO = new ArrayList<>();
        }
        isInitPlay = true;
        playerListDTO = playListBean.getPlayerList();
        playVideo();
        videoType = playListBean.getVideoType();
        if ("综艺".equals(playListBean.getVideoType())) {
            rlBigPartBox.setLayoutManager(new GridLayoutManager(this, 1));
        }


        //        for (PlayListBean.PlayerListDTO listDTO : playerList) {
        //            if (listDTO.getPlayerType() == 20) {
        //                playerListDTO.add(listDTO);
        //            }
        //        }
    }

    @Override
    public void getPlayAddress(String playUrl) {
        svPlayBox.setPlayTime(playTime);
        svPlayBox.setVideoUrl(playUrl);
        RlVideoPlayError.setVisibility(View.GONE);
    }

    @Override
    public void getPlayAddressError() {
        //        playVideo(true, false);
        RlVideoPlayError.setVisibility(View.VISIBLE);
    }

    @Override
    public void showDayHot(List<MovieBean> categoryBeans) {
        llLikeBox.setVisibility(View.VISIBLE);
        likeAdapter.setDataList(categoryBeans);
        likeAdapter.notifyDataSetChanged();
    }

    @Override
    public void showNoMore() {
        llLikeBox.setVisibility(View.GONE);
    }


    private void addHistory(MovieBean movieBean) {
        if (movieBean == null) {
            return;
        }
        PlayHistoryBean newPlayHistory = null;
        for (int i = 0; i < playHistories.size(); i++) {
            PlayHistoryBean playHistory = playHistories.get(i);
            if (playHistory.getMovieId() == movieBean.getId()) {
                newPlayHistory = playHistory;
                playHistories.remove(i);
                break;
            }
        }
        if (newPlayHistory == null) {
            newPlayHistory = new PlayHistoryBean();
        }

        newPlayHistory.setMovieId(movieBean.getId());
        newPlayHistory.setPartIndex(partIndex);
        newPlayHistory.setPlayTime(playTime);
        newPlayHistory.setSaveTime(System.currentTimeMillis());
        newPlayHistory.setMovieBean(movieBean);
        try {
            newPlayHistory.setPartName(partAdapter.getDataList().get(partIndex).getInfoName());
        } catch (Exception ignore) {
            LoggerUtil.e("记录集数名称失败");
        }

        playHistories.add(0, newPlayHistory);
        while (playHistories.size() >= Contents.PLAY_HISTORY_SIZE) {
            playHistories.remove(Contents.PLAY_HISTORY_SIZE - 1);
        }
        MyApplication.aCache.put(Contents.CACHE_KEY_HISTORY, JSON.toJSONString(playHistories));

    }
}
